package com.qf.service.impl;

import com.alipay.api.internal.util.AlipaySignature;
import com.qf.dao.OrderRepository;
import com.qf.pojo.respVo.BaseResp;
import com.qf.pojo.vo.QfOrder;
import com.qf.service.AlipayService;
import com.qf.utils.AlipayUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    OrderRepository orderRepository;

    @Autowired
    AlipayUtils alipayUtils;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public BaseResp pay(String orderid) {
        //传入了oderid，通过orderid获取到 该订单的信息
        Optional<QfOrder> byId = orderRepository.findById(orderid);
        if (!byId.isPresent()){
            return new BaseResp(0,"没有该订单！",null,null);
        }
        QfOrder qfOrder = byId.get();
        //开始声明支付宝的内容
        String pay = alipayUtils.pay(qfOrder);
        //存储下现在订单的到期支付的时间

        //修改订单的状态，由未支付更改为正在支付
        qfOrder.setOrderStatus(3);
        //进行修改操作
        orderRepository.saveAndFlush(qfOrder);
        //将该笔订单的信息交给rabbitmq的延迟队列，设置过期时间为 3分钟
        rabbitTemplate.convertAndSend("dead-pay-exchange", "dead-pay", orderid, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置该条信息的过期时间
                message.getMessageProperties().setExpiration("180000");
                return message;
            }
        });
        return new BaseResp(1,"请求成功！",pay,null);
    }

    @Override
    public void callBack(HttpServletRequest request) {
        Map map = alipayUtils.callBack(request);
        //说明验签成功，是支付宝回调，我们就可以进行状态的修改操作
       if (map!=null){
           //1.从支付宝的回调接口中获取到 当前订单的id
           String out_trade_no = map.get("out_trade_no").toString();
           //2.获取到支付的金额
           Double total_amount = Double.valueOf(map.get("total_amount").toString());
            //3.获取到数据库中的订单信息
           Optional<QfOrder> byId = orderRepository.findById(out_trade_no);
           if (byId.isPresent()){
               QfOrder qfOrder = byId.get();
               //判断支付的回调金额与数据库的金额是否一直
               if (qfOrder.getOrderPay().compareTo(total_amount)==0){
                   //修改支付的状态
                   qfOrder.setOrderStatus(2);
                   orderRepository.saveAndFlush(qfOrder);
               }
           }
       }

    }
}
